package common;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * Created with IntelliJ IDEA
 * Descroption
 * User:dell
 * Date:2025-09-07
 * Time:14:32
 */
public class Utils {
    public static WebDriver webDriver = null;
    public WebDriverWait wait = null;

    public Utils(String url){
        webDriver = createDriver();
        if(url != null){
            webDriver.get(url);
        }
        wait = new WebDriverWait(webDriver, Duration.ofSeconds(3));

    }

    /**
     * 创建浏览器驱动
     * @return
     */
    public static WebDriver createDriver(){
        if (webDriver == null){
            //加载本地驱动
            System.setProperty("webdriver.edge.driver", "E:\\download\\Driver\\edgedriver_win64\\msedgedriver.exe");
            //添加配置，允许远程访问
            EdgeOptions options = new EdgeOptions();
            options.addArguments("--remote-allow-origins=*");
            // 关键修改：禁止浏览器自动关闭未处理的Alert
            options.setCapability("unhandledPromptBehavior", "ignore");
            //创建驱动对象
            webDriver = new EdgeDriver(options);

            //添加隐式等待-只等待页面元素
            webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return webDriver;
    }

    /**
     * 屏幕截图
     * 截图文件目录
     * ./src/test/java/images/
     *                       /yyyy-MM-dd/
     *                                  /test01-HH-mm-ss-SS.png
     */
    public void ScreenShot(String str) throws IOException {
        //年月日
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        //时分秒
        SimpleDateFormat sim2 = new SimpleDateFormat("HH-mm-ss-SS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());


        //图片文件名：路径+图片名称

        String fileName = "./src/test/java/images/"+dirTime+"/"+str+"-"+fileTime+".png";
        File srcFile = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile,new File(fileName));
    }

    /**
     * 销毁webDriver对象——关闭浏览器
     */
    public static void quit(){
        if (webDriver != null){
            webDriver.quit();
        }
    }
}
